#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import binascii
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
import modbus_tk.defines as cst
import modbus_tk.modbus_rtu as modbus_rtu
from com.zxy.z_debug import z_debug
class ModBusClient(z_debug):
    def __init__(self, runType, ServerIP, temPort):
        self.srunType = runType
        self.sServerIP = ServerIP
        self.iPort = temPort
    def _getCrc16(self, RtuStr):
        b = 0xA001
        a = 0xFFFF
        for byte in RtuStr:
            a = a ^ byte
            for i in range(8):
                if a & 0x0001:
                    a = a >> 1
                    a = a ^ b 
                else:
                    a = a >> 1
        print(a)
        aa = '0' * (6 - len(hex(a))) + hex(a)[2:]
        print(aa)
        lo, hh = int(aa[:2], 16), int(aa[2:], 16)
        print(hex(hh),hex(lo))
        hexbytes = bytes([hh, lo])
        return hexbytes
    def get_data_com(self):         
        try:  
            com_at = Com_Fun.GetHashTable(Com_Para.htComPort,"A")  
            CmdStr = "010300000009"#85CC"
            inputByte  = bytes().fromhex(CmdStr)
            inputByte = inputByte+self._getCrc16(inputByte)
            if com_at.WritePortData(inputByte) > 0:
                comValue = com_at.attReturnValue
                temReturn = str(binascii.b2a_hex(comValue))[2:-1]                    
                temReturn = " ".join([temReturn[e:e+2] for e in range(0,len(temReturn),2)])                    
                com_at.attReturnValue = None
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            Data = -1
        return Data 
    def get_data_rtu(self):
        red = []
        alarm = ""
        try:
            com_at = Com_Fun.GetHashTable(Com_Para.htComPort,"A")
            master = modbus_rtu.RtuMaster(com_at.attSerial)                         
            master.set_timeout(5.0)
            master.set_verbose(True)
            red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)  # 这里可以修改需要读取的功能码
            print(red)
            alarm = "正常"
            return list(red), alarm    
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            alarm = (str(e))
            return red, alarm                    